package com.mdnote.structure.stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/24
 * @description 后缀表达式（逆波兰）
 */
public class PostfixExpressionCalc {

    // 表达式
    private String express;

    // 操作数字和符号的几何
    private List<String> items;

    public PostfixExpressionCalc(String express) {
        this.express = express;
        this.items = convert(express);
    }

    public PostfixExpressionCalc(List<String> items) {
        this.items = items;
    }

    private List<String> convert(String express) {
        List<String> rtn = new ArrayList<>();
        String[] splits = express.split(" ");

        return  Arrays.asList(splits);
    }

    public int calculate() {
        Stack<Integer> numberStack = new Stack<>();

        for (String item : this.items) {
            // 判断是否为符号
            if (item.charAt(0) < 48 || item.charAt(0) > 57) {
                // 如果是符号则弹出两个数字进行运算
                Integer n1 = numberStack.pop();
                Integer n2 = numberStack.pop();
                numberStack.push(Operation.calculate(n2, n1, item.charAt(0)));
            } else {
                // 如果是数字直接压入
                numberStack.push(Integer.valueOf(item));
            }

        }
        return numberStack.peek();
    }

    public static void main(String[] args) {
        PostfixExpressionCalc postfixExpressionCalc = new PostfixExpressionCalc("3 4 + 5 * 6 -");
        System.out.println(postfixExpressionCalc.calculate());
    }
}
